package com.dtsz.m2.ui.notifications;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.android.volley.Request;
import com.bumptech.glide.Glide;
import com.cxy.library.entity.BannerEntity;
import com.cxy.library.iutils.IBannerBaseAdapter;
import com.cxy.library.view.BannerView;
import com.dtsz.m2.R;
import com.dtsz.m2.config.UrlConfig;
import com.dtsz.m2.provider.DataUtils;
import com.dtsz.m2.ui.activity.ActivityPasswordActivity;
import com.dtsz.m2.ui.activity.DownActivity;
import com.dtsz.m2.ui.activity.IdentificationCardTvActivity;
import com.dtsz.m2.ui.activity.LoginActivity;
import com.dtsz.m2.ui.activity.NoticeActivity;
import com.dtsz.m2.ui.activity.QuotaActivity;
import com.dtsz.m2.ui.activity.RetrievePasswordActivity;
import com.dtsz.m2.ui.activity.TaskAttestationActivity;
import com.dtsz.m2.ui.base.BaseFragment;
import com.dtsz.m2.ui.model.CertificationVo;
import com.dtsz.m2.ui.model.RegisterVo;
import com.dtsz.m2.ui.model.Users;
import com.dtsz.m2.utils.StringUtils;
import com.dtsz.m2.volley.state.HUCState;

import java.util.List;

public class NotificationsFragment extends BaseFragment {
    private final String TAG = NotificationsFragment.class.getSimpleName();
    private TextView tvName, tvNickName, tvPhone, tvCode, tvNameUser;
    private String phone;
    private String name;
    private String biIm, card;
    private String buCertification;
    private Switch switch1;
    private Users users;

    private FrameLayout container;
    private BannerView bannerView;
//    private ShowBannerAD showBannerAD;
    private LinearLayout llIdentification;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View root = inflater.inflate(R.layout.fragment_notifications, container, false);
        llIdentification = root.findViewById(R.id.ll_identification);
        root.findViewById(R.id.ll_money).setOnClickListener(this);
        root.findViewById(R.id.ll_price).setOnClickListener(this);
        root.findViewById(R.id.ll_exit).setOnClickListener(this);
        root.findViewById(R.id.ll_ver).setOnClickListener(this);
        root.findViewById(R.id.ll_service).setOnClickListener(this);
        root.findViewById(R.id.ll_swdj).setOnClickListener(this);
        root.findViewById(R.id.ll_url).setOnClickListener(this);
        root.findViewById(R.id.ll_book).setOnClickListener(this);
        root.findViewById(R.id.ll_lxwm).setOnClickListener(this);
        root.findViewById(R.id.ll_zh).setOnClickListener(this);
        root.findViewById(R.id.ll_phone).setOnClickListener(this);
        tvName = root.findViewById(R.id.tv_name);
        tvNickName = root.findViewById(R.id.tv_nickname);
        tvPhone = root.findViewById(R.id.tv_phone);
        tvCode = root.findViewById(R.id.tv_code);
        switch1 = root.findViewById(R.id.switch1);
        tvNameUser = root.findViewById(R.id.tv_name_user);
        bannerView = root.findViewById(R.id.id_bannerView);
        container = root.findViewById(R.id.container);
        switch1.setOnClickListener(this);
//        showBannerAD = new ShowBannerAD(getActivity(), container);
//        showBannerAD.setShowBannerADListener(new ShowBannerADListener() {
//            @Override
//            public void onNoAD(int errorCode) {
//                Log.i(TAG, "onNoAD errorCode : " + errorCode);
//            }
//
//            @Override
//            public void onADReceive() {
//                Log.i(TAG, "onADReceive");
//
//            }
//
//            @Override
//            public void onADExposure() {
//                Log.i(TAG, "onADExposure");
//            }
//
//            @Override
//            public void onADClosed() {
//                Log.i(TAG, "onADClosed");
//                showBannerAD.destroy();
//            }
//
//            @Override
//            public void onADClicked() {
//                Log.i(TAG, "onADClicked");
//            }
//        });
        bannerView();
        return root;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hucRequestInterfase.cancelAll();
//        if (showBannerAD != null)
//            showBannerAD.destroy();
    }

    public void showBanner(View view) {
//        if (showBannerAD != null) {
//            showBannerAD.loadAD("6000030");
//        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_identification:
                initData2();
                break;
            case R.id.ll_money:
                sendIntent(getActivity(), NoticeActivity.class);
                break;
            case R.id.ll_ver:
                sendIntent(getActivity(), DownActivity.class);
                break;
            case R.id.ll_service:
                //sendIntent(getActivity(), ServiceActivity.class);
                sendUrl("https://m2.app/jrwm");
                break;
            case R.id.ll_lxwm:
                //sendIntent(getActivity(), ServiceActivity.class);
                sendUrl("https://m2.app/lxwm");
                break;
            case R.id.ll_swdj:
                sendUrl("https://m2.app/swdj");
                //sendIntent(getActivity(), CooperationActivity.class);
                break;
            case R.id.ll_book:
                sendUrl("https://m2.app/bps");
                //sendIntent(getActivity(), CooperationActivity.class);
                break;
            case R.id.ll_url:
                if (users != null) {
                    Intent intentUrl = new Intent();
                    intentUrl.setClass(getActivity(), ActivityPasswordActivity.class);
                    startActivity(intentUrl);
                }
                break;
            case R.id.ll_price:
                Intent intent = new Intent();
                intent.setClass(getActivity(), RetrievePasswordActivity.class);
                intent.putExtra("phone", phone);
                getActivity().startActivityForResult(intent, HUCState.HUC_REQEUST_CODE_1);
                break;
            case R.id.ll_exit:
                getActivity().finish();
                setSharedPreferences("tokenRSA", "token001");
                DataUtils.deleteToken(getActivity());
                sendIntent(getActivity(), LoginActivity.class);
                break;
            case R.id.switch1:
                getSwitch();
                break;
            case R.id.ll_zh:
                getBindUserName(tvName.getText().toString());
                break;
            case R.id.ll_phone:
                getBindUserPhone();
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == HUCState.HUC_REQEUST_CODE_1) {
            if (data != null) {
                String msg = data.getStringExtra("msg");
                if ("保存成功".equals(msg)) {
                    setSharedPreferences("tokenRSA", "token001");
                    DataUtils.deleteToken(getActivity());
                    sendIntent(getActivity(), LoginActivity.class);
                    getActivity().finish();
                }
            }
        }
    }

    class LoopPhotoAdapter implements IBannerBaseAdapter {
        Context context;
        List<BannerEntity> data;

        public LoopPhotoAdapter(Context context, List<BannerEntity> entities) {//构造方法
            this.context = context;
            data = entities;
        }

        @Override
        public void loadImage(String url, ImageView imageView) {//加载图片
            if (context != null) {
                Glide.with(context).load(url).into(imageView);
            }
        }

        @Override
        public int setItemCount() {//数据个数
            return data.size();
        }

        @Override
        public List<BannerEntity> setData() {//设置数据
            return data;
        }

        @Override
        public void onItemClick(int position) {//点击事件
            BannerEntity bannerEntity = data.get(position);
            String url = bannerEntity.getBarUrl();
            if (!"0".equals(url)) {
                sendUrl(url);
            }

        }
    }

    private void bannerView() {
        pageVo.setType("6");
        hucRequestInterfase.executeStr(this, BannerEntity.class,
                HUCState.HUC_REQEUST_CODE_5, Request.Method.POST, UrlConfig.BANNER_URL,
                hucParameInterfase.getRequestParameter(pageVo), false);
    }


    private void initData() {
        hucRequestInterfase.executeStr(this, Users.class,
                HUCState.HUC_REQEUST_CODE_1, Request.Method.POST, UrlConfig.USERS_URL,
                hucParameInterfase.getRequestParameter(pageVo), true);
    }

    @Override
    public void onErrorLogin(int inputType) {
        super.onErrorLogin(inputType);
        setSharedPreferences("tokenRSA", "token001");
        getActivity().finish();
        sendIntent(getActivity(), LoginActivity.class);
    }


    @Override
    public void onStart() {
        super.onStart();
        initData();
    }


    @Override
    public void onSuccessfulStrType(int inputType, Object response) {
        super.onSuccessfulStrType(inputType, response);
        switch (inputType) {
            case HUCState.HUC_REQEUST_CODE_1:
                if (response instanceof Users) {
                    Users user = (Users) response;
                    users = user;
                    biIm = user.getBuIm();
                    llIdentification.setOnClickListener(NotificationsFragment.this);
                    buCertification = user.getBuCertification();
                    name = user.getBuName();
                    card = user.getBuCard();
                    phone = user.getBuPhone();
                    String buMail = user.getBuMail();
                    if (StringUtils.isEmpty(buMail)) {
                        tvNameUser.setHint("请设置账号");
                    } else {
                        tvName.setText(buMail);
                        tvNameUser.setText(buMail);
                    }
                    String name = user.getBuName();
                    tvNickName.setText(name);
                    tvCode.setText(user.getBuCode());
                    tvPhone.setText(user.getBuPhone());
                    String huHidden = user.getBuHidden();
                    switch1.setChecked("1".equals(huHidden));
                } else {
                    Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_SHORT).show();
                }
                break;
            case HUCState.HUC_REQEUST_CODE_2:
                if (response instanceof CertificationVo) {
                    CertificationVo certificationVo = (CertificationVo) response;
                    if (certificationVo != null) {
                        String state = certificationVo.getBcState();
                        if ("-1".equals(state) || "不存在".equals(certificationVo.getBcDescription())) {
                            if ("0".equals(biIm) || StringUtils.isEmpty(biIm)) {//领取名额
                                sendIntent(getActivity(), QuotaActivity.class);
                            } else {
                                sendIntent(getActivity(), TaskAttestationActivity.class);
                            }
                        } else {
                            Intent intent1 = new Intent();
                            intent1.setClass(getActivity(), IdentificationCardTvActivity.class);
                            intent1.putExtra("name", certificationVo.getBcName());
                            intent1.putExtra("phone", certificationVo.getBcPhone());
                            intent1.putExtra("card", certificationVo.getBcCard());
                            intent1.putExtra("yhk", certificationVo.getBcYhk());
                            startActivity(intent1);
                        }
                    }
                } else {
                    showToast(response.toString());
                }
                break;
            case HUCState.HUC_REQEUST_CODE_3:
                showToast(response.toString());
                break;
            case HUCState.HUC_REQEUST_CODE_4:
                String msg = response.toString();
                if ("保存成功".equals(msg)) {
                    alertDialog1.dismiss();
                    tvName.setText(etUserName.getText().toString());
                    tvNameUser.setText(etUserName.getText().toString());
                }
                showToast(msg);
                break;
            case HUCState.HUC_REQEUST_CODE_5:
                if (response instanceof List) {
                    List<BannerEntity> bannerEntityList = (List<BannerEntity>) response;
                    if (bannerEntityList != null && bannerEntityList.size() > 0) {
                        LoopPhotoAdapter loopPhotoAdapter = new LoopPhotoAdapter(getActivity(), bannerEntityList);
                        if (bannerEntityList.size() <= 1) {
                            bannerView.setRl_point_group(View.GONE);
                        }
                        bannerView.setVisibility(View.VISIBLE);
                        bannerView.setAdapter(loopPhotoAdapter);
                    } else {
                        bannerView.setVisibility(View.GONE);
                    }
                } else {
                    showToast(response.toString());
                }
                break;
            case HUCState.HUC_REQEUST_CODE_6:
                String msgCode = (String) response;
                if ("绑定成功".equals(msgCode)) {
                    setSharedPreferences("phone", etUsers.getText().toString());
                    tvPhone.setText(etUsers.getText().toString());
                    alertDialog1.dismiss();
                }
                showToast(msgCode);
                break;
        }
        loadDismiss();
    }


    private void getSwitch() {
        Users users = new Users();
        users.setToken(pageVo.getToken());
        users.setBuHidden(switch1.isChecked() ? "1" : "0");
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_3, Request.Method.POST, UrlConfig.SET_SWITCH_URL,
                hucParameInterfase.getRequestParameter(users), true);
    }

    private EditText etUserName, etUsers, etPhone;
    AlertDialog alertDialog1;

    private void getBindUserName(String userName) {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.item_user_name, null);
        dialog.setView(root);
        etUserName = root.findViewById(R.id.et_name);
        if (!StringUtils.isEmpty(userName)) {
            etUserName.setText(userName);
        }
        root.findViewById(R.id.tv_ok).setOnClickListener(v -> {
            String tvNa = etUserName.getText().toString();
            if (StringUtils.isEmpty(tvNa)) {
                showToast("账号不能为空");
            } else {
                getBindName(tvNa);
            }

        });
        root.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog1.setCancelable(false);
        alertDialog1.show();
    }

    private void getBindName(String name) {
        Users users = new Users();
        users.setToken(pageVo.getToken());
        users.setBuMail(name);
        loading();
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_4, Request.Method.POST, UrlConfig.BINDNAME_URL,
                hucParameInterfase.getRequestParameter(users), true);
    }


    private void getBindUserPhone() {
        //判断是否绑定姓名
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        // dialog.setTitle("绑定姓名");
        View root = LayoutInflater.from(getActivity()).inflate(R.layout.item_up_phone, null);
        dialog.setView(root);
        etUsers = root.findViewById(R.id.et_user);
        etPhone = root.findViewById(R.id.et_phone);
        root.findViewById(R.id.tv_ok).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tvNa = etUsers.getText().toString();
                if (!StringUtils.isMobile(tvNa)) {
                    showToast("手机号码格式错误！");
                    return;
                }
                if (!tvNa.equals(etPhone.getText().toString())) {
                    showToast("手机号码不一致");
                    return;
                }
                getBindPhoneUrl(tvNa);

            }
        });
        root.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = dialog.create();
        alertDialog1.getWindow().setBackgroundDrawableResource(R.color.transparent);
        alertDialog1.setCancelable(false);
        alertDialog1.show();
    }

    public void getBindPhoneUrl(String phone) {
        RegisterVo registerVo = new RegisterVo();
        registerVo.setToken(pageVo.getToken());
        registerVo.setPhone(phone);
        hucRequestInterfase.executeStr(this, String.class,
                HUCState.HUC_REQEUST_CODE_6, Request.Method.POST, UrlConfig.BINDPHONE_URL,
                hucParameInterfase.getRequestParameter(registerVo), true);
    }

    private void initData2() {
        loading();
        hucRequestInterfase.executeStr(this, CertificationVo.class, HUCState.HUC_REQEUST_CODE_2, Request.Method.POST, UrlConfig.ISCERTIFICATION_URL, hucParameInterfase.getRequestParameter(pageVo), true);
    }

}
